package com.jt.ktdemo.ui.myinfo

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.Window
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.databinding.DataBindingUtil
import com.bumptech.glide.Glide
import com.jt.ktdemo.R
import com.jt.ktdemo.bean.BackBean
import com.jt.ktdemo.bean.PersonCallbackBean
import com.jt.ktdemo.bean.UpdatePersonelInfomationBean
import com.jt.ktdemo.databinding.UserinfoBinding
import com.jt.ktdemo.dialog.DateDialog
import com.jt.ktdemo.dialog.GenderDialog
import com.jt.ktdemo.http.HTTPAPI
import com.jt.ktdemo.listener.OnDialogSelectListener
import com.jt.ktdemo.ui.EditActivity
import com.jt.ktdemo.utils.Constants.Companion.NUM_NAME
import com.jt.ktdemo.utils.GsonUtils
import com.jt.ktdemo.utils.LogUtil
import com.jt.ktdemo.utils.SpUtils
import com.lcw.library.imagepicker.ImagePicker
import com.lcw.library.imagepicker.loader.GlideLoader
import com.lzy.okgo.callback.StringCallback
import okhttp3.Call
import okhttp3.Response
import java.io.File


class MyInfoActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var binding: UserinfoBinding
    private var firstEditText: Boolean = false
    private var secondEditText: Boolean = false
    private var thirdEditText: Boolean = false
    private var forthEditText: Boolean = false
    private var fivethEditText: Boolean = false
    private var fixthEditText: Boolean = false
    private var seventEditText: Boolean = false
    private lateinit var name: String
    private var FROM_ALBUM_SUCCEED: Int = 0x11
    private var imagePaths: ArrayList<String> = ArrayList()
    private var mS_imgUrl = Environment.getExternalStorageDirectory().absolutePath + "/"
    private lateinit var uid: String

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = DataBindingUtil.setContentView(this, R.layout.userinfo)
        binding.activity = this
        binding.btModuleLogin.setBackgroundResource(R.drawable.draw_module_login_bg_selected)
        initView();
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun initView() {
        name = SpUtils["module_name", ""].toString()
        uid = SpUtils["module_uid", ""].toString()

        LogUtil.e("用户Uid-->" + uid)
        if (!TextUtils.isEmpty(uid)) {
            mS_imgUrl += uid + ".png"
            binding.cdModule.visibility = View.VISIBLE
            Glide.with(this)
                .load("http://ec2-13-59-112-96.us-east-2.compute.amazonaws.com:8080/face/home/ubuntu/face/" + uid + ".png")
                .into(binding.ivMdoule)
        } else {
            LogUtil.e("uid空")
        }
        binding.ivModuleBack.setOnClickListener {
            finish()
        }
        binding.rlModuleHead.setOnClickListener {
            ImagePicker.getInstance()
                .setTitle("图片") //设置标题
                .showCamera(true) //设置是否显示拍照按钮
                .showImage(true) //设置是否展示图片
                .showVideo(false) //设置是否展示视频
                .filterGif(true) //设置是否过滤gif图片
                .setSingleType(true) //设置图片视频不能同时选择
                .setMaxCount(1) //设置最大选择图片数目(默认为1，单选)
                .setImageLoader(GlideLoader(this)) //设置自定义图片加载器
                .start(this, FROM_ALBUM_SUCCEED)
        }

        binding.etModuleName.setOnClickListener(this)
        binding.etModuleGender.setOnClickListener(this)
        binding.etModuleHeight.setOnClickListener(this)
        binding.etModuleWeight.setOnClickListener(this)
        binding.etModuleBloodType.setOnClickListener(this)
        binding.etModuleBirthday.setOnClickListener(this)

        binding.btModuleLogin.setOnClickListener {
            //获取Boolean准确数据
            initTextViewStatus()

            if (firstEditText && secondEditText && thirdEditText && forthEditText && fivethEditText && fixthEditText && seventEditText) {
                var name = binding.etModuleName.text.toString().trim()
                var gender = binding.etModuleGender.text.toString().trim()
                var height = binding.etModuleHeight.text.toString().trim().replace("厘米","")
                var weight = binding.etModuleWeight.text.toString().trim().replace("kg","")
                var booldType = binding.etModuleBloodType.text.toString().trim()
                var birthday = binding.etModuleBirthday.text.toString().trim()

                if (TextUtils.isEmpty(name)) {
                    Toast.makeText(this, "Please enter your name", Toast.LENGTH_LONG).show()
                } else if (TextUtils.isEmpty(gender)) {
                    Toast.makeText(this, "Please enter your gender", Toast.LENGTH_LONG).show()
                } else if (TextUtils.isEmpty(height)) {
                    Toast.makeText(this, "Please enter your height", Toast.LENGTH_LONG).show()
                } else if (TextUtils.isEmpty(weight)) {
                    Toast.makeText(this, "Please enter your weight", Toast.LENGTH_LONG).show()
                } else if (TextUtils.isEmpty(booldType)) {
                    Toast.makeText(this, "Please enter your booldType", Toast.LENGTH_LONG).show()
                } else if (TextUtils.isEmpty(birthday)) {
                    Toast.makeText(this, "Please enter your birthday", Toast.LENGTH_LONG).show()
                } else {
                    update(name, gender, birthday, height, weight, booldType)
                }
            }
        }

        //获取个人信息
        getPersion();
    }

    /**
     *
     */
    public fun update(
        name: String,
        gender: String,
        birthday: String,
        height: String,
        weight: String,
        booldType: String
    ) {
        var bean: UpdatePersonelInfomationBean = UpdatePersonelInfomationBean()
        bean.setName(name)
        bean.setGender(gender)
        bean.setBirthday(birthday)
        bean.setHeight(Integer.valueOf(height))
        bean.setWeight(Integer.valueOf(weight))
        bean.setBloodType(booldType)

        LogUtil.e("提交-->" + GsonUtils.toJson(bean))

        HTTPAPI.updatePersonnelInfomation(bean, object : StringCallback() {
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                LogUtil.e("密码更新成功-->$t")
                var bean: BackBean = GsonUtils.parse(t.toString(), BackBean::class.java)
                if (!TextUtils.isEmpty(bean.session)) {
                    SpUtils.put("module_session", bean.session)
                }
                Toast.makeText(
                    this@MyInfoActivity,
                    "Personal information updated successfully!",
                    Toast.LENGTH_SHORT
                ).show()
                finish()
            }

            override fun onError(call: Call?, response: Response?, e: Exception?) {
                LogUtil.e("密码更新失败-->${e!!.message}")
            }
        })
    }

    @SuppressLint("NewApi")
    fun checkBoolean() {
        initTextViewStatus()
        if (firstEditText && secondEditText && thirdEditText && forthEditText && fivethEditText && fixthEditText && seventEditText) {
            binding.btModuleLogin.setBackgroundResource(R.drawable.draw_module_login_bg)
        } else {
            LogUtil.e("firstEditText->$firstEditText")
            LogUtil.e("secondEditText->$secondEditText")
            LogUtil.e("thirdEditText->$thirdEditText")
            LogUtil.e("forthEditText->$forthEditText")
            LogUtil.e("fivethEditText->$fivethEditText")
            LogUtil.e("fixthEditText->$fixthEditText")
            LogUtil.e("seventEditText->$seventEditText")
            binding.btModuleLogin.setBackgroundResource(R.drawable.draw_module_login_bg_selected)
        }
    }

    /**
     * 获取Boolean值
     */
    fun initTextViewStatus() {
        firstEditText = !TextUtils.isEmpty(binding.etModuleName.text.toString().trim())
        secondEditText = !TextUtils.isEmpty(binding.etModuleName.text.toString().trim())
        thirdEditText = !TextUtils.isEmpty(binding.etModuleGender.text.toString().trim())
        forthEditText = !TextUtils.isEmpty(binding.etModuleHeight.text.toString().trim())
        fivethEditText = !TextUtils.isEmpty(binding.etModuleWeight.text.toString().trim())
        fixthEditText = !TextUtils.isEmpty(binding.etModuleBloodType.text.toString().trim())
        seventEditText = !TextUtils.isEmpty(binding.etModuleBirthday.text.toString().trim())
    }


    @SuppressLint("MissingSuperCall")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                FROM_ALBUM_SUCCEED -> {
                    imagePaths =
                        data!!.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES) as ArrayList<String>
                    val uri: Uri = if (Build.VERSION.SDK_INT >= 24) {
                        // 适配android7.0 ，不能直接访问原路径
                        FileProvider.getUriForFile(
                            this,
                            getPackageName().toString() + ".fileProvider",
                            File(imagePaths.get(0))
                        )
                    } else {
                        Uri.fromFile(File(imagePaths.get(0)))
                    }
                    LogUtil.e("图片路径-->" + imagePaths.get(0))
                    startPhotoZoom(uri)
                    binding.cdModule.visibility = View.VISIBLE
                    Glide.with(this).load(imagePaths.get(0)).into(binding.ivMdoule)
                }

                //名称修改
                NUM_NAME -> {
                    binding.etModuleName.text = data?.getStringExtra("module_result")
                    checkBoolean()
                }
                4 -> {
                    updateFace(File(mS_imgUrl))
                }
            }
        }
    }

    /**
     * 调用系统裁剪
     *
     * @param uri
     */
    private fun startPhotoZoom(uri: Uri) {
        val intent = Intent("com.android.camera.action.CROP")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        //裁剪后输出路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(File(mS_imgUrl)))
        //输入图片路径
        intent.setDataAndType(uri, "image/*")
        intent.putExtra("crop", "true")
        intent.putExtra("aspectX", 1)
        intent.putExtra("aspectY", 1)
        intent.putExtra("outputX", 300)
        intent.putExtra("outputY", 300)
        intent.putExtra("scale", true)
        intent.putExtra("scaleUpIfNeeded", true)
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString())
        intent.putExtra("return-data", false)
        startActivityForResult(intent, 4)
    }

    fun updateFace(file: File) {
        HTTPAPI.updateHeadPhoto(file, object : StringCallback() {
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                LogUtil.e("人脸图片上传成功-->$t")
            }

            override fun onError(call: Call?, response: Response?, e: Exception?) {
                LogUtil.e("人脸图片上传失败-->${e?.message}")
            }
        })
    }

    /**
     * 获取个人信息
     */
    fun getPersion() {
        HTTPAPI.getPersion(object : StringCallback() {
            @SuppressLint("SetTextI18n")
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                LogUtil.e("个人信息-->$t")
                try {
                    var bean: PersonCallbackBean =
                        GsonUtils.parse(t.toString(), PersonCallbackBean::class.java)
                    binding.etModuleName.text = bean.rcUser?.username
                    binding.etModuleGender.text = bean.rcUser?.gender
                    binding.etModuleHeight.text = bean.rcUser?.height.toString() + "cm"
                    binding.etModuleWeight.text = bean.rcUser?.weight.toString() + "kg"
                    binding.etModuleBirthday.text = bean.rcUser?.birthday
                    binding.etModuleEmail.text = bean.rcUser?.email
                    binding.etModuleBloodType.text = bean.rcUser?.bloodType
                } catch (e: java.lang.Exception) {
                    Toast.makeText(this@MyInfoActivity, "联网返回值异常-->$t", Toast.LENGTH_LONG).show()
                }
            }

            override fun onError(call: Call?, response: Response?, e: java.lang.Exception?) {
                LogUtil.e("个人信息获取失败-->${e!!.message}")
            }
        })
    }

    /**
     * 身高
     * 体重
     * 性别
     * 生日
     * 血性
     */
    override fun onClick(v: View?) {
        var id = v?.id
        when (id) {
            R.id.etModuleBirthday -> {
                showTimeDialog()
            }
            R.id.etModuleBloodType -> {
                showBloodTypeDialog()
            }
            R.id.etModuleWeight -> {
                showWeightDialog()
            }
            R.id.etModuleHeight -> {
                showHeightDialog()
            }
            R.id.etModuleGender -> {
                showGenderDialog()
            }
            R.id.etModuleName -> {
                var intentName = Intent(this, EditActivity::class.java)
                intentName.putExtra("module_type", "name")
                intentName.putExtra("module_name",binding.etModuleName.text.toString().trim())
                startActivityForResult(intentName, NUM_NAME)
            }
        }
    }

    /**
     * 显示时间选择弹窗
     */
    private fun showTimeDialog() {
        val dateDialog = DateDialog(this)
        dateDialog.setGravity(Gravity.BOTTOM)
        dateDialog.show()
        dateDialog.setOnDialogSelectListener(object : OnDialogSelectListener {
            override fun setOnDialogSelectListener(listBeans: String?) {
                LogUtil.e("选择日期-->" + listBeans)
                binding.etModuleBirthday.setText(listBeans)
                dateDialog.dismiss()
                checkBoolean()
            }
        })

    }

    /**
     * 显示性别选择弹窗
     */
    private fun showGenderDialog() {
        val genderDialog = GenderDialog(this)
        genderDialog.setGravity(Gravity.BOTTOM)
        genderDialog.show()
        genderDialog.setGenderList()
        genderDialog.setOnDialogSelectListener(object : OnDialogSelectListener {
            override fun setOnDialogSelectListener(listBeans: String?) {
                LogUtil.e("选择性别-->" + listBeans)
                binding.etModuleGender.text = listBeans
                genderDialog.dismiss()
                checkBoolean()
            }
        })
    }

    /**
     * 显示身高选择弹窗
     */
    private fun showHeightDialog() {
        val heightDialog = GenderDialog(this)
        heightDialog.setGravity(Gravity.BOTTOM)
        heightDialog.show()
        heightDialog.setHeightList()
        heightDialog.setOnDialogSelectListener(object : OnDialogSelectListener {
            override fun setOnDialogSelectListener(listBeans: String?) {
                LogUtil.e("选择身高-->" + listBeans)
                binding.etModuleHeight.setText(listBeans+"cm")
                heightDialog.dismiss()
                checkBoolean()
            }
        })
    }

    /**
     * 显示体重选择弹窗
     */
    private fun showWeightDialog() {
        val heightDialog = GenderDialog(this)
        heightDialog.setGravity(Gravity.BOTTOM)
        heightDialog.show()
        heightDialog.setWeightList()
        heightDialog.setOnDialogSelectListener(object : OnDialogSelectListener {
            override fun setOnDialogSelectListener(listBeans: String?) {
                LogUtil.e("选择体重-->" + listBeans)
                binding.etModuleWeight.setText(listBeans + "kg")
                heightDialog.dismiss()
                checkBoolean()
            }
        })
    }

    /**
     * 显示血型选择弹窗
     */
    private fun showBloodTypeDialog() {
        val heightDialog = GenderDialog(this)
        heightDialog.setGravity(Gravity.BOTTOM)
        heightDialog.show()
        heightDialog.setBloodTypeList()
        heightDialog.setOnDialogSelectListener(object : OnDialogSelectListener {
            override fun setOnDialogSelectListener(listBeans: String?) {
                LogUtil.e("选择血型-->" + listBeans)
                binding.etModuleBloodType.setText(listBeans)
                heightDialog.dismiss()
                checkBoolean()
            }
        })
    }
}